import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/acl/login'
import router from '@/router'
import _ from 'lodash'
import { useRoute } from 'vue-router';
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
//计算出当前用户将来需要动态追加的异步路由结果  
const findRouters = (allAsyncRoutes: any, routes: any) => {
  return allAsyncRoutes.filter((item: any) => {
    if (routes.indexOf(item.name) != -1) {
      if (item.children && item.children.length > 0) {
        item.children = findRouters(item.children, routes)
      }
      return true
    }
  })
}

export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],//左侧菜单栏的数据
    buttonList:[]
  }),

  actions: {
    //登录
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password })
        this.token = result.token
        //持久化存储数据
        setToken(this.token)
        return 'ok'
      } catch (error) {
        return Promise.reject('error')
      }
    },
    //获取用户数据
    async getInfo() {
      try {
        let result = await reqUserInfo()
        console.log(result)
        this.name = result.name
        this.avatar = result.avatar
        this.buttonList=result.buttons
        //计算当前异步路由需要返回的数据
        let userRoute = findRouters(_.cloneDeep(allAsyncRoutes), result.routes)

        //调用方法
        this.setRoute([...userRoute, anyRoute])
        this.menuRoutes = [...staticRoutes,...userRoute]
        return 'ok'

      } catch (error) {
        return Promise.reject('error')
      }
    },
      //动态添加路由
      setRoute(registerRoute:any){
        //用户A:B:C：最终需要动态追加的路由
        registerRoute.forEach((item:any)=>{
            router.addRoute(item);
        })
   }
   ,

    //退出登录
    async reset() {
      try {
      await reqLogOut()
        //清除本地token
        removeToken()
        //清除仓库里面的数据
        this.token = ''
        this.name = ''
        this.avatar = ''
         //重置路由
         this.resetRoute();
        return 'ok'

      } catch (error) {
        return Promise.reject('error')
      }

    },
        //重置路由方法
        resetRoute() {
          //当前用户退出登录，应该清空掉全部异步路由
          //获取当前用户全部路由信息
          let allRoutes = router.getRoutes();
          //用户退出登录:全部的路由清除
          allRoutes.forEach((item: any) => {
            //全部删除路由
            router.removeRoute(item.name);
          });
          //常量路由:动态添加上
          staticRoutes.forEach((item: any) => {
            router.addRoute(item);
          });
        }
  },
});
